<template>
  <div class="select-none">
    <img :src="bg" class="wave">
    <div class="login-container">
      <div class="img">
        <svg-icon icon-class="illustration" class-name="img-illustration"/>
      </div>
      <div class="login-box">
        <div class="login-form">
          <svg-icon icon-class="xmut" class-name="img-avatar"/>
          <h2 class="outline-none">{{appTitle}}</h2>
          <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
            
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" clearable placeholder="账号" prefix-icon="user"/>
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" clearable show-password placeholder="密码" prefix-icon="Lock"/>
            </el-form-item>
            
            <el-form-item v-if="captchaEnabled" prop="code">
              <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" size="large"
                        style="width: 63%" @keyup.enter="handleLogin">
                <template #prefix>
                  <svg-icon #prefix icon-class="validCode"/>
                </template>
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" alt=""/>
              </div>
            </el-form-item>
            
            <el-form-item prop="rememberMe">
              <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-button class="w-full mt-4" size="default" type="primary" :loading="loading" @click.prevent="handleLogin">
                <span v-if="!loading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </el-form-item>

          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>

import bg from '@/assets/image/bg.png'
import Cookies from "js-cookie";
import {decrypt, encrypt} from "@/utils/jsencrypt.js";
import {getCodeImg} from "@/api/login.js";

const appTitle = import.meta.env.VITE_APP_TITLE

const userStore = useUserStore();
const router = useRouter();
const route = useRoute()
const loginFormRef = ref()

const loginForm = ref({
  username: "admin",
  password: "admin123",
  code: '',
  uuid: '',
  rememberMe: false
});
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const loading = ref(false);
const codeUrl = ref("");
const captchaEnabled = ref(false)
const redirect = ref(null)

// 监听重定向到登录页的页面,登录后可以返回到之前的页面
watch(
    route, () => redirect.value = route?.query?.redirect,
    {immediate: true}
)



const handleLogin = function () {

  loginFormRef.value.validate(valid => {
    if (valid) {
      loading.value = true
      //记住我?
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username)
        Cookies.set("password", encrypt(loginForm.value.password))
        Cookies.set("rememberMe", loginForm.value.rememberMe)
      } else {
        Cookies.remove("username")
        Cookies.remove("password")
        Cookies.remove("rememberMe")
      }
      userStore.login(loginForm.value)
          .then(res => {
            router.push({path: redirect.value || "/"}).catch(e => console.error(e))
          })
          .catch(e => getCode())
          .finally(() => loading.value = false)
    }
  })

}

const getCode = () => {
  loginForm.value.code = ''
  getCodeImg().then(res => {
    captchaEnabled.value = res.data?.captchaEnabled ?? true
    if (captchaEnabled.value) {
      codeUrl.value = `data:image/gif;base64,${res.data.img}`
      loginForm.value.uuid = res.data.uuid
    }
  })
}

const getCookie = () => {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

getCode()
getCookie()

</script>

<style lang="scss" scoped>
//不能选择文本
.select-none {
  -webkit-user-select: none;
  -moz-user-select: none;
  user-select: none;
}

//背景图
.wave {
  position: fixed;
  height: 100%;
  width: 80%;
  left: 0;
  bottom: 0;
  z-index: -1;
}

.img {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .img-illustration {
    width: 500px;
    height: 380px;
  }

}

.login-container {
  width: 100vw;
  height: 100vh;
  max-width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 18rem;
  padding: 0 2rem;

  .login-box {
    display: flex;
    align-items: center;
    text-align: center;
    overflow: hidden;

    .login-form {
      width: 360px;

      .img-avatar {
        width: 350px;
        height: 80px;
      }

      h2 {
        text-transform: uppercase;
        margin: 15px 0;
        color: #999;
        font: bold 200% Consolas,
        Monaco,
        monospace;
      }


    }

  }

}

.login-code {
  width: 33%;
  height: 40px;
  float: right;
  margin-left: 12px;

  img {
    cursor: pointer;
    vertical-align: middle;
    height: 40px;
  }
}

@media screen and (max-width: 1180px) {
  .login-container {
    grid-gap: 9rem;
  }

  .login-form {
    width: 290px;
  }

  .login-form h2 {
    font-size: 2.4rem;
    margin: 8px 0;
  }

  .img .img-illustration {
    width: 360px;
  }

  .avatar {
    width: 280px;
    height: 80px;
  }
}

@media screen and (max-width: 968px) {
  .wave {
    display: none;
  }

  .img {
    display: none;
  }

  .login-container {
    grid-template-columns: 1fr;
  }

  .login-box {
    justify-content: center;
  }
}

:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

</style>
